#include "gifwidget.h"
#include "ui_gifwidget.h"
#include <QPainter>
#include <QTimer>
#include <QImage>

GifWidget::GifWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::GifWidget),
    m_count(0),
    m_duration(0)
{
    ui->setupUi(this);

    m_timer = new QTimer(this);
    connect(m_timer, SIGNAL(timeout()), this, SLOT(refresh()));
    png =new QImage(this->size(),QImage::Format_ARGB32);
}

GifWidget::~GifWidget()
{
    m_timer->stop();
    delete png;
    delete ui;
}

QList<QString> GifWidget::files() const
{
    return m_files;
}

void GifWidget::setFiles(const QList<QString> &files)
{
    m_files = files;
}

void GifWidget::refresh()
{
    png->load(m_files.at(m_count),"png");
    update();
    m_count = (m_count+1) % m_files.count();
}

void GifWidget::paintEvent(QPaintEvent *e)
{
    Q_UNUSED(e);
    QPainter p(this);
    p.drawImage(this->rect(),*png);
}

void GifWidget::showEvent(QShowEvent *e)
{
    refresh();
    m_timer->start(m_duration/m_files.count());
    QWidget::showEvent(e);
}

void GifWidget::hideEvent(QHideEvent *e)
{
    m_timer->stop();
    QWidget::hideEvent(e);
}

int GifWidget::duration() const
{
    return m_duration;
}

void GifWidget::setDuration(int duration)
{
    m_duration = duration;
}


